﻿using QGZX.Helper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;


namespace QGZX.Logic
{
    public class UpLoadController : Controller
    {
        public ActionResult Index()
        {
            Response.ContentType = "text/plain";
            Response.Charset = "UTF-8";

            // 身份认证

            HttpFileCollection filecollection = System.Web.HttpContext.Current.Request.Files;
            HttpPostedFile fileData = filecollection.Get("fileData");

            // 上传文件保存路径，结尾不带/
            string attachdir = "/Upload";
            // 1：按天存；2：按月存；3：按扩展名存
            int dirtype = 1;
            // 最大上传大小，默认10M
            int maxattachsize = 2097152 * 10;
            // 允许的扩展名
            string upext = "txt,rar,zip,doc,docx,xls,xlsx,ppt,pptx,pdf,swf,jpg,jpeg,gif,png,bmp,wmv,avi,rm,mp4,wma,mp3,mid";
            // 返回上传参数的格式：1只返回url，2返回参数数组
            int msgtype = 2;
            // 统一将文件转为字节数组处理
            byte[] file;

            // 本地文件名
            string localname = string.Empty;
            // 获取MIME协议的扩展内容
            string disposition = Request.ServerVariables["HTTP_CONTENT_DISPOSITION"];

            // 错误信息
            string err = string.Empty;
            // 返回信息
            string msg = string.Empty;

            if (disposition != null)
            {
                // HTML5上传
                file = Request.BinaryRead(Request.TotalBytes);
                localname = Server.UrlDecode(Regex.Match(disposition, "filename=\"(.+?)\"").Groups[1].Value);
            }
            else
            {
                // 读取原始文件名
                localname = fileData.FileName;
                // 初始化文件长度
                file = new byte[fileData.ContentLength];
                // 转为字节数组
                System.IO.Stream stream = fileData.InputStream;
                stream.Read(file, 0, fileData.ContentLength);
                stream.Close();
            }

            if (file.Length == 0) err = "无数据提交";
            else
            {
                if (file.Length > maxattachsize) err = "文件大小超过" + maxattachsize + "字节";
                else
                {
                    string attach_dir, attach_subdir, filename, extension, target;

                    // 取上载文件后缀名
                    extension = GetFileExt(localname);

                    if (("," + upext + ",").IndexOf("," + extension + ",") < 0) err = "上传文件扩展名必需为：" + upext;
                    else
                    {
                        switch (dirtype)
                        {
                            case 2:
                                attach_subdir = "month_" + DateTime.Now.ToString("yyMM");
                                break;
                            case 3:
                                attach_subdir = "ext_" + extension;
                                break;
                            default:
                                attach_subdir = "day_" + DateTime.Now.ToString("yyMMdd");
                                break;
                        }
                        attach_dir = attachdir + "/" + attach_subdir + "/";

                        // 生成随机文件名
                        Random random = new Random(DateTime.Now.Millisecond);
                        filename = DateTime.Now.ToString("yyyyMMddhhmmss") + random.Next(10000, 100000) + "." + extension;

                        target = attach_dir + filename;
                        try
                        {
                            CreateFolder(Server.MapPath("~/" + attach_dir));

                            System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath("~/" + target), System.IO.FileMode.Create, System.IO.FileAccess.Write);
                            fs.Write(file, 0, file.Length);
                            fs.Flush();
                            fs.Close();
                        }
                        catch (Exception ex)
                        {
                            err = ex.Message.ToString();
                        }

                        target = jsonString(target);

                        // 考虑了虚拟目录的问题 by xm 2013-5-28
                        if (msgtype == 1) msg = "'" + target + "'";
                        else msg = "{'url':'" + (Request.ApplicationPath == "/" ? "" : Request.ApplicationPath) + target + "','localname':'" + jsonString(localname) + "','id':'1'}";
                    }
                }
            }

            file = null;

            Response.Write("{'err':'" + jsonString(err) + "','msg':" + msg + "}");
            //return this.Content("{'err':'" + jsonString(err) + "','msg':" + msg + "}");
            return null;
        }
        string GetFileExt(string FullPath)
        {
            if (FullPath != "") return FullPath.Substring(FullPath.LastIndexOf('.') + 1).ToLower();
            else return "";
        }
        string jsonString(string str)
        {
            str = str.Replace("\\", "\\\\");
            str = str.Replace("/", "\\/");
            str = str.Replace("'", "\\'");
            return str;
        }
        void CreateFolder(string FolderPath)
        {
            if (!System.IO.Directory.Exists(FolderPath)) System.IO.Directory.CreateDirectory(FolderPath);
        }


        public ActionResult HandleUpload()
        {
            Response.ContentType = "text/plain";

            // upload files
            HttpPostedFileBase fileData = Request.Files["Filedata"];

            if (fileData != null)
            {
                string result = null;
                try
                {
                    // 取上载文件后缀名
                    string extension = GetFileExt(fileData.FileName);
                    string upext = "txt,rar,zip,doc,docx,xls,xlsx,ppt,pptx,pdf,swf,jpg,jpeg,gif,png,bmp,wmv,avi,rm,mp4,wma,mp3,mid";
                    if (("," + upext + ",").IndexOf("," + extension + ",") < 0)
                    {
                        result = "不允许的文件类型";
                        Response.Write(result);
                        Response.End();
                        return null;
                    };

                    string fileExt = Path.GetExtension(fileData.FileName);
                    string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + fileExt;

                    string RelativeDir = "/Upload/License/";

                    string dir = Server.MapPath(RelativeDir);

                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }
                    fileData.SaveAs(Path.Combine(dir, fileName));
                    result = RelativeDir + fileName;
                }
                catch
                {
                    result = null;
                }
                Response.Write(result);
            }
            return null;
        }
    }
}
